export function toast(title = "", config = {}) {
  let {
    icon = 'none', mask = true, duration = 2000, success, fail, complete
  } = config;
  uni.showToast({
    title,
    icon,
    mask,
    duration,
    success,
    fail,
    complete
  })
}

export function $toast(title = '') {
  toast(title)
}
['success', "error", "loading"].forEach((icon) => {
  $toast[icon] = (title = '', callback) => {
    toast(title, {
      icon,
      complete: callback
    })
  }
})
// 检查数据类型
export function checkType(parmas) {
  return Object.prototype.toString.call(parmas).slice(8, -1).toLowerCase()
}
// JSON字符串转为js数据
export function jsonParse(parmas) {
  if (checkType(parmas) === 'string') {
    try {
      return JSON.parse(parmas)
    } catch (e) {
      return false
    }
  }
  return false
}
// 判断数据是否为空 例如 null undefined, 空字符串 '',空数组[], 空对象{}
export function isEmpty(parmas) {
  let type = checkType(parmas);
  if (type === 'null' || type === 'undefined') return true;
  if (type === 'string' || type === 'array') return parmas.length === 0;
  if (type === 'object') return Object.keys(parmas).length === 0;
  if (type === 'number') return false
}
// 深度拷贝数据
export function deepClone(data) {
  let type = checkType(data),
    res;
  if (type === 'array') {
    res = [];
    for (let i = 0; i < data.length; i++) {
      res.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    res = {}
    for (let key in data) {
      if (data.hasOwnProperty(key)) {
        res[key] = deepClone(data[key])
      }
    }
  } else {
    res = data
  }
  return res;
}
// 正则验证对象
export const pattern = {
  allNumber: /^\d{1,}$/, // 1位以上纯数字验证
  verifiCode: /^\d{6}$/, // 6位纯数字验证
  phone: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, // 手机号验证
  pwd: /^\d{8}$/, // 8位纯数字验证
  loginName: /^\d{4}$/, // 4位纯数字验证
  password: /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{8,16})$/, //8到16位 同时包含字母(无论大小写)和数字 
  password1: /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?.,_]).{6,16}$/, // 8到16位，至少1个大写字母，1个小写字母,1个数字和1个特殊字符
  password2: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/, // 8到16位，至少1个大写字母，1个小写字母和1个数字,不能包含特殊字符
  amount: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, // 金额数字验证，但包含0，0.0或0.00
  idCard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, //身份证验证
  email: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, // 邮箱验证
}
// 前位补0
function addStrBeforeNum(s) {
  return s < 10 ? '0' + s : s
}
// 获取距离 start 时间点 前或者后 intervel 天的时间
export function getIntervalTime(intervel = 0, start = null) {
  let now = checkType(start) === 'date' ? start : new Date();
  intervel = parseInt(intervel);
  now.setDate(now.getDate() + intervel);
  let keys = ['getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds'],
    res = {};
  keys.forEach(key => {
    let num = now[key]();
    if (key === 'getMonth') num = num + 1
    res[key] = addStrBeforeNum(num)
  })
  res.dateTime = `${res.getFullYear}-${res.getMonth}-${res.getDate} ${res.getHours}:${res.getMinutes}:${res.getSeconds}`
  res.date = `${res.getFullYear}-${res.getMonth}-${res.getDate}`
  return res
}
// 防抖  immediate 为true 时 防抖函数不延时，立即执行
export function debounce(callback, wait = 1000, immediate = false) {
  let timeout = null;
  return (...args) => {
    let callNow = immediate && !timeout;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      timeout = null;
      if (!immediate) callback.call(this, ...args);
    }, wait);
    if (callNow) callback.call(this, ...args);
  };
}
// 节流
export function throttle(callback, delay = 1000) {
  let last = null;
  return (...args) => {
    let now = (new Date()).getTime()
    if (!last) {
      callback.call(this, ...args)
      last = now
    } else {
      let delays = now - last
      if (delays > delay) {
        callback.call(this, ...args)
        last = now
      }
    }
  }
}
// 对象序列化查询参数字符串
export function queryStringify(data = {}) {
  if (isEmpty(data)) return '';
  let res = Object.keys(data).reduce((str, key) => {
    let val = isEmpty(data[key]) ? '' : data[key]
    return str += `${key}=${val}&`
  }, '?')
  if (isEmpty(res)) res = '';
  return res.slice(0, res.length - 1)
}
// 格式化数字，返回浮点数
export function toFixed(num = 0, float = 2) {
  if (isEmpty(num)) num = 0;
  let r = isNaN(parseFloat(num)) ? 0 : parseFloat(num);
  return r.toFixed(float)
}
// 求和 getSum(1,2,3)
export function getSum() {
  let sum = [...arguments].reduce((total, num) => {
    num = toFixed(num).replace('.', '');
    return total += parseInt(num)
  }, 0)
  return toFixed(sum / 100)
}

export function getProvider(service = 'oauth') {
  const serviceList = ['oauth', "share", 'payment', 'push'];
  service = serviceList.includes(service) ? service : 'oauth';
  return new Promise((resolve, reject) => {
    uni.getProvider({
      service,
      success(res) {
        resolve({
          provider: res.provider,
          service: res.service
        })
      },
      fail(err) {
        reject({
          provider: ["weixin"],
          service: "oauth"
        })
      }
    });
  })
}

// 获取微信code
export function getAuthCode() {
  return new Promise(async (resolve, reject) => {
    let providerData = await getProvider()
    uni.login({
      provider: providerData.provider[0] || 'weixin', //使用微信登录
      scopes: 'auth_base',
      onlyAuthorize: true,
      success(res) {
        resolve({
          code: res.code,
        })
      },
      fail(err) {
        reject(err)
      }
    });
  })
}